package com.raychi.demo.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

import com.raychi.demo.entity.Category;
import com.raychi.demo.util.CategoryUtil;

public class CategoryDao {
	public List<Category> getCategorys(Connection conn) throws Exception{
		List<Category> categorys = new ArrayList<Category>();
		Statement st = conn.createStatement();
		ResultSet rs = st.executeQuery("select * from Category");
		Category category = null;
		while(rs.next()){
			category = CategoryUtil.creatCategory(rs);
			categorys.add(category);
		}
		return categorys;
	}
	
	public void delete(Category category, Connection conn) throws Exception{
		Statement st = conn.createStatement();
		String sql = "delete from Category where id="+category.getId();
		st.execute(sql);
	}
	
	public void update(Category category, Connection conn) throws Exception{
		String sql = "update Category set name = ?, listOrder = ?, proCount = ? where id = ?";
		PreparedStatement ps = conn.prepareStatement(sql);
		ps.setString(1, category.getName());
		ps.setInt(2, category.getListOrder());
		ps.setInt(3, category.getProCount());
		ps.setInt(4, category.getId());
		ps.executeUpdate();
	}
	
	public void save(Category category, Connection conn) throws Exception{
		String sql = "insert into Category (name, listOrder, proCount) values (?,?,?)";
		PreparedStatement ps = conn.prepareStatement(sql);
		ps.setString(1, category.getName());
		ps.setInt(2, category.getListOrder());
		ps.setInt(3, category.getProCount());
		ps.execute();
	}
}
